from django.shortcuts import render
from .models import News,NewsCategory,Comment
from .serializers import NewsSerializers,CommentsSerializers
from utils import restful
from django.conf import settings
from apps.xfzauth.decorators import xfz_login_required
from .forms import CommentsForm
from django.db.models import Q
from apps.news.models import Banner
# Create your views here.

def index(request):
    count = settings.ONE_PAGE_NEWS_COUNT
    newses = News.objects.select_related('category','author').all()[0:count]
    categories = NewsCategory.objects.all()
    context = {
        'newses': newses,
        'categories': categories,
        'banners': Banner.objects.all()
    }
    return render(request,'news/index.html',context=context)


def news_list(request):
    page = int(request.GET.get('p',1)) #默认第一页
    # 0 2    1    2
    # 2 4    2    2
    # 4 6
    start = (page-1)*settings.ONE_PAGE_NEWS_COUNT
    end = start+settings.ONE_PAGE_NEWS_COUNT

    category_id = int(request.GET.get('category_id',0))
    if category_id == 0:
        newses = News.objects.select_related('category','author').all()[start:end]
    else:
        newses = News.objects.select_related('category', 'author').filter(category__id=category_id)[start:end]
    serializer = NewsSerializers(newses,many=True)
    data = serializer.data
    return restful.result(data=data)


def news_detail(request,news_id):
    news = News.objects.select_related('category','author').prefetch_related("comments__author").get(pk=news_id)
    context = {
        'news':news
    }
    return render(request,'news/news_detail.html',context=context)

@xfz_login_required
def public_comment(request):
    form  = CommentsForm(request.POST)
    if form.is_valid():
        news_id = form.cleaned_data.get('news_id')
        content = form.cleaned_data.get('content')
        news = News.objects.get(pk=news_id)
        comment = Comment.objects.create(content=content,news=news,author=request.user)
        serializer = CommentsSerializers(comment)
        return restful.result(data=serializer.data)
    else:
        return restful.params_error(message=form.get_errors())


def search(request):
    q = request.GET.get('q')
    context = {

    }
    if q:
        newses = News.objects.filter(Q(title__icontains=q) | Q(content__icontains=q))
        print(newses)
        context['newses'] = newses
    return render(request, 'search/search1.html', context=context)


